/**
 * 读取目录结构生成路由配置
 */
import { RouteItemRecord, RouteItem } from '@/domain/router';
import routeConfig from './config';

const getDirRoutes = (): RouteItem[] => {
    const routes: RouteItem[] = [];
    const modules: Record<string, () => Promise<any>> = import.meta.glob("@/views/**/*.vue");
    for (const [pathKey, moduleImport] of Object.entries(modules)) {
        if (pathKey.includes('components') || pathKey.includes('layouts')) {
            continue;
        }
        const matchResult = pathKey.match(/\/views\/(.*?)\.vue$/);
        if (!matchResult) {
            continue;
        }
        const pageName = matchResult[1];
        let idArr = pageName.split('/'), id = idArr[idArr.length - 1];
        const { name = id, meta = {} }: RouteItemRecord = routeConfig[pageName] || {};
        routes.push({
            path: '/' + pageName,
            name,
            id,
            component: () => moduleImport().then(m => m.default), // 正确处理默认导出
            meta
        });
    }
    return routes;
}

const routes = getDirRoutes();

export default routes;